/**
 * 创建真实DOM
 * @param {*} vnode 
 */
function createEl(vnode) {
  let { vm, tag, children, key, data, text } = vnode;
  if (typeof tag === 'string') {
    vnode.el = document.createElement(tag);

    if (createComopnent(vnode)) {
      return vnode.componentInstance.$el;
    } else {
      if (children.length > 0) {
        children && children.forEach(child => {
          // 递归添加子元素
          vnode.el.appendChild(createEl(child));
        })
      }
    }

  } else {
    vnode.el = document.createTextNode(text);
  }
  return vnode.el;
}

/**
 * 创建组件真实dom
 * @param {*} vnode 
 */
function createComopnent(vnode) {
  let i = vnode.data;
  if ((i = i.hook) && (i = i.init)) {
    i(vnode);
  }
  if (vnode.componentInstance) {
    return true;
  }
  return false
}

/**
 * 替换真实DOM   //todo diff算法
 * @param {*} oldVnode 
 * @param {*} vnode 
 * @returns 
 */
export function patch(oldVnode, vnode) {
  if (!oldVnode) { return createEl(vnode) }
  let el = createEl(vnode);
  let parentEl = oldVnode.parentNode;
  parentEl.insertBefore(el, oldVnode.nextsibling);
  parentEl.removeChild(oldVnode);
  return el;
}